import { HealthCheckWithScreenTask } from "./health.check.class";
import { V3proSubjectMessage } from "../model/v3pro.model";
import {
  HealthEnum,
  V3proAlertMessageErrTypeEnum,
  V3proExternalDeviceTypeEnum,
} from "../model/v3pro.enum";
import {
  v3proScreenExternalDeviceListApi,
  v3proScreenExternalDeviceStatusApi,
} from "../../../api/v3pro-api/v3pro.screen.api";
import { logger } from "../../../configs/log.config";
import {
  V3proExternalDeviceStatus,
  V3proScreen,
  V3proScreenAllStatus,
} from "../../../api/v3pro-api/v3pro.api.response.model";
import { equals } from "ramda";
import { V3proFileHelper } from "../helper/v3pro.file.helper";
import { appConfig } from "../../../configs/env.config.load";

/**
 * 亮度传感器故障
 *
 * 是否支持阈值设置： N
 *
 * 查询周期:
 * 定时查询
 * 间隔15秒
 *
 * 告警产生的原因:
 * 亮度传感器采集到的环境亮度不随环境亮度变化或变化不大
 *
 * 异常现象:
 * 显示屏亮度不随环境亮度变化
 *
 * 维修建议:
 * 依次检查亮度传感器接线、多功能卡
 *
 * 告警级别: 次要
 */

export class V3proCheckLumSensorTask extends HealthCheckWithScreenTask<
  V3proExternalDeviceStatus[]
> {
  async checkResult(
    keyParams: any,
    screenId: string,
    allStatus: V3proScreenAllStatus,
  ): Promise<V3proSubjectMessage> {
    const message = new V3proSubjectMessage();
    if (!keyParams.length) return message;
    message.setErrStatus();
    message.files = [await V3proFileHelper.externalDeviceKey2File(keyParams)];
    return message;
  }

  async genKeyParams(
    allScreenStatus: V3proScreenAllStatus,
    screen: V3proScreen,
  ): Promise<V3proExternalDeviceStatus[]> {
    const typeEqualsLightSensor = equals(V3proExternalDeviceTypeEnum.SENSOR_BRIGHT);
    const healthEqualsAbnormal = equals(HealthEnum.ABNORMAL);
    try {
      const list = await v3proScreenExternalDeviceListApi(screen.id, this.__addCancelToken());
      const ans = [];
      for (const item of list) {
        if (!typeEqualsLightSensor(item.type)) continue;
        const info = await v3proScreenExternalDeviceStatusApi(item.id, this.__addCancelToken());
        if (healthEqualsAbnormal(info.health)) ans.push(info);
      }
      return ans;
    } catch (e) {
      logger.error("读取亮度传感器故障失败", e);
    }
    return [];
  }

  genSRMqttTopic(
    message: V3proSubjectMessage,
    screenId: string,
    allStatus: V3proScreenAllStatus,
  ): string {
    return `notify/alert/ssads/device-sensor:photosensor-fault/${screenId}`;
  }

  getV3proAlertMessage(): V3proAlertMessageErrTypeEnum {
    return V3proAlertMessageErrTypeEnum.LUM_SENSOR;
  }

  isNeedUploadFile(
    message: V3proSubjectMessage,
    screenId: string,
    allStatus: V3proScreenAllStatus,
  ): boolean {
    return message.isErrStatus();
  }

  isReportEnabled(keyParams: any, screenId: string): boolean {
    return appConfig.v3pro.errEnable.panelLuminance;
  }

  getInterval(): number {
    return appConfig.v3pro.collectTimer.lux * 1000;
  }
}
